package com.steve.summary.seata.service.impl;

import com.steve.summary.seata.entity.Account;
import com.steve.summary.seata.mapper.AccountMapper;
import com.steve.summary.seata.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @Author: STEVE
 * @Description: 账户服务实现
 * @since: 2025-07-09
 */
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    /**
     * 扣减账户余额
     *
     * @param userId 用户ID
     * @param money  扣减金额
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decrease(String userId, BigDecimal money) {
        log.info("-------> 开始扣减账户余额");

        // 检查账户余额
        Account account = accountMapper.selectByUserId(userId);
        if (account == null) {
            throw new RuntimeException("账户不存在");
        }
        if (account.getBalance().compareTo(money) < 0) {
            throw new RuntimeException("余额不足");
        }

        // 扣减余额
        accountMapper.deductBalance(userId, money);

        log.info("-------> 扣减账户余额完成");
    }

    /**
     * 获取账户信息
     *
     * @param userId 用户ID
     * @return 账户信息
     */
    @Override
    public Account getByUserId(String userId) {
        return accountMapper.selectByUserId(userId);
    }

    /**
     * 恢复账户余额
     *
     * @param userId 用户ID
     * @param money  恢复金额
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increase(String userId, BigDecimal money) {
        log.info("-------> 开始恢复账户余额");
        Account account = accountMapper.selectByUserId(userId);
        if (account != null) {
            accountMapper.restoreBalance(userId, money);
        }
        log.info("-------> 恢复账户余额完成");
    }

}
